// miniprogram/pages/info/zmyygzs/zmyygzs.js
var app = getApp();
var util = require('../../../utils/util.js');
var  input_id,  zy_memo ;
var laifangmudi, beifangzhekeshi, beifangzhename, flag="1";
var    workaddress,  workphone,  startwhere,  crosswhere,  traininfo,  train_memo; // 下面火车 站信息用
Page({  
  /**
   * 页面的初始数据
   */
  data: {
    lxbx04zhengzhuangH: true,
    hsfwc: true,
    btnEn: false, 
    twocode_en :true,
 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  
  onLoad: function (options) {

    this.zmyygzs_lxbx();

    this.lxbx04();
    this.sfwc_check();
    this.sex_radio();
    this.hospital_mz_lcbx();
    this.findOpenid();
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../../chooseLib/chooseLib',
      })
      return
    }

  },

  //拍照或者从相册选择要识别的照片
  photo(type) {
    let that = this

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], ///'original',压缩图
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        let imgUrl = res.tempFilePaths[0];
        // console.log("photo", imgUrl)
        that.uploadImg(app.globalData.openid + new Date().getTime(), imgUrl)
        
      }
    })
  },

  // 上传图片到云存储
  uploadImg(type, imgUrl) {
    let that = this
    wx.cloud.uploadFile({
      cloudPath: 'ocr/' + type + '.png',
      filePath: imgUrl, // 文件路径
      success: res => {
        // console.log("上传成功", res.fileID)
        that.getImgUrl(type, res.fileID)
      },
      fail: err => {
        // console.log("上传失败", err)
      }
    })
  },

  //获取云存储里的图片url
  getImgUrl(type, imgUrl) {
    wx.showToast({
      title: '正在识别',
      icon: 'loading'
    })
    let that = this
    wx.cloud.getTempFileURL({
      fileList: [imgUrl],
      success: res => {
        let imgUrl = res.fileList[0].tempFileURL
        // console.log("获取图片url成功", imgUrl)
        that.shibie(type, imgUrl)
      },
      fail: err => {
        // console.log("获取图片url失败", err)
      }
    })
  },

  //调用云函数，实现OCR识别
  shibie(type, imgUrl) {
    // console.log("识别成功shibie", type)
    let that = this
    wx.cloud.callFunction({
      name: "photo",
      data: {
        type: "shenfenzheng",
        imgUrl: imgUrl
      },
      success(res) {
        // console.log("识别成功", res)
        switch (res.result.gender) {

          case "男":
            that.setData({
              name: res.result.name,
              sfz: res.result.id,
              address: res.result.addr,
              sex_radio: [{checked:true, anme: "男", value: "男"},
                { checked: false, anme: "女", value: "女" }]
            })
            break;
          case "女":
            that.setData({
              name: res.result.name,
              sfz: res.result.id,
              address: res.result.addr,
              sex_radio: [{ checked: false, anme: "男", value: "男" },
              { checked: true, anme: "女", value: "女" }]
            })
            break;          
        }
        
        
      },
      fail(res) {
        // console.log("识别失败", res)
      }
    })
    // console.log("识别成功res.result.name")


  }
  ,
  twocode_en_false: function () {
    // console.log("修改")
    this.setData({
      twocode_en: true,
      btnEn: false,
    })
  },
  reset: function (e) {
    // const db = wx.cloud.database()
    console.log('修改数据　：', e)
    // console.log('修改数据　zmyygzs_lxbx：', zmyygzs_lxbx)
    // db.collection('base_zmyy').doc(input_id).remove({
    //   success: function (res) {
        
    //   }
    // })
    // this.formSubmit();
  },
  sfwc_check: function (e) {
    // console.log('马上查询数据库，findcheckbox为:')
    const db = wx.cloud.database();
    var that = this;
    db.collection('checkbox').doc('zmyygzs_sfwc').get({
      success: function (res) {
        // res.data 包含该记录的数据
        // console.log('findcheckbox为:', res.data.lxbx)
        that.setData({
          sfwc_check: res.data.sfwc,
        })
      }
    })
  },
  hospital_mz_lcbx: function (e) {
    // console.log('马上查询数据库，findcheckbox为:')
    const db = wx.cloud.database();
    var that = this;
    db.collection('checkbox').doc('hospital_mz_lcbx').get({
      success: function (res) {
        that.setData({
          hospital_mz_lcbx: res.data.lcbx,
        })
      }
    })
  },
  lxbx04: function (e) {
    // console.log('马上查询数据库，findcheckbox为:')
    const db = wx.cloud.database();
    var that = this;
    db.collection('checkbox').doc('zmyygzs_lxbx04').get({
      success: function (res) {
        // res.data 包含该记录的数据
        // console.log('findcheckbox为:', res.data.lxbx)
        // console.log('this.data.items为:', res.data.lxbx04)
        that.setData({
          lxbx04zhengzhuang: res.data.lxbx04,
        })
      }
    })
  },

  sfwc: function (e) {
    var vsfwc = e.detail.value
    if (vsfwc != "") {
      this.setData({
        hsfwc: false,
        twocode_en: true,
        btnEn: false,
      })
    }
    else {
      this.setData({
        hsfwc: true,
        twocode_en: true,
        btnEn: false,
      })
    }
  },
  zmyygzs_lxbx :function (e){
    // console.log('马上查询数据库，findcheckbox为:')
    const db = wx.cloud.database();
    var that =this;
    db.collection('checkbox').doc('zmyygzs_lxbx').get({
      success: function (res) {
        // res.data 包含该记录的数据
        // console.log('findcheckbox为:', res.data.lxbx)
        // console.log('this.data.items为:', that.data.items)
        that.setData({
          zmyygzs_lxbx: res.data.lxbx,
        })
      }
    })
  },
  // },
  //确定按钮点击事件
  // modalBindaconfirm: function () {
  //   this.setData({
  //     // modalHidden: !this.data.modalHidden,
  //     textHeid: false
  //   })

  // },
  sex_radio: function (e) {
    // console.log('马上查询数据库，findcheckbox为:')
    const db = wx.cloud.database();
    var that = this;
    db.collection('checkbox').doc('sex').get({
      success: function (res) {
        // console.log('马上查询数据库，findcheckbox为:', res.data.sex)
        that.setData({
          sex_radio: res.data.sex,
        })
      }
    })
  },
    getPhoneNumber(e) {
    var that = this;
    wx.cloud.callFunction({
      name: 'getPhone',
      data: {
        weRunData: wx.cloud.CloudID(e.detail.cloudID),
        twocode_en: true,
        btnEn: false,
      }
    }).then(res => {
      this.setData({
        phone: res.result,
        twocode_en: true,
        btnEn: false,
      })
    }).catch(err => {
    });
  },

  
  createTwoCode: function () {
    wx.redirectTo({
      url: '/pages/createTwoCode/createTwoCode'
    })
  },
  twocode_en_false: function () {
    // console.log("修改")
    this.setData({
      twocode_en: true,
      btnEn: false,
    })
  },
  
  findOpenid: function () {
    const db = wx.cloud.database();
    wx.cloud.callFunction({
      name: 'login',
      complete: res => {
        app.globalData.openid = res.result.openid
        db.collection('base_zmyy').where({
          _openid: app.globalData.openid
        }).limit(1)
        .orderBy('addtime', 'desc')//按字段排序
          .get()
          .then(res => {

            // console.log('查询数据库，data:', res.data)
            if (res.data.length) {
              // console.log('查询数据库，data:', res.data[0])
              let arrlxbx = [], arrlxbx04 = [], arrsex = [], arrsfwc = [], arrzhengzhuang =[];  //存放选中id的数组
                        let json;
              try { 
              if (res.data[0].lxbx != "") {
                          for (let i = 0; i < this.data.zmyygzs_lxbx.length; i++) {
                            if (res.data[0].lxbx.includes(this.data.zmyygzs_lxbx[i].value)) {
                              // 全选获取选中的值
                              json = { "checked": true, "name": this.data.zmyygzs_lxbx[i].name, "value": this.data.zmyygzs_lxbx[i].value }
                              // arrlxbxv.push(json.value)
                            }
                            else {
                              json = { "checked": false, "name": this.data.zmyygzs_lxbx[i].name, "value": this.data.zmyygzs_lxbx[i].value }    
                            }
                            arrlxbx.push(json);
                            
                          }
                        }
                        else {
                          for (let i = 0; i < this.data.zmyygzs_lxbx.length; i++) {

                            json = { "checked": false, "name": this.data.zmyygzs_lxbx[i].name, "value": this.data.zmyygzs_lxbx[i].value }
                            arrlxbx.push(json);                            
                          }
                        }
                this.setData({
                  zmyygzs_lxbx: arrlxbx,
                }) 
              } catch {
                
               }


              try { 
              if (res.data[0].sex != "") {
                          for (let i = 0; i < this.data.sex_radio.length; i++) {
                            if (res.data[0].sex.includes(this.data.sex_radio[i].name)) {
                              // 全选获取选中的值
                              json = { "checked": true, "name": this.data.sex_radio[i].name, "value": this.data.sex_radio[i].value }
                            }
                            else {
                              json = { "checked": false, "name": this.data.sex_radio[i].name, "value": this.data.sex_radio[i].value }
                            }
                            arrsex.push(json);
                          }
                        }
                        else {
                          for (let i = 0; i < this.data.sex_radio.length; i++) {
                            json = { "checked": false, "name": this.data.sex_radio[i].name, "value": this.data.sex_radio[i].value }
                            arrsex.push(json);
                          }
                        }
                this.setData({                
                  sex_radio: arrsex,                 

                })   
              } catch {
              }
             
              try { 
              if (res.data[0].lxbx04zhengzhuang　!="") {
             
                this.setData({
                  lxbx04zhengzhuangH: false,
                }) 
                for (let i = 0; i < this.data.lxbx04zhengzhuang.length; i++) {
                  if (res.data[0].lxbx04zhengzhuang.includes(this.data.lxbx04zhengzhuang[i].value)) {
                    // 全选获取选中的值
                    json = { "checked": true, "name": this.data.lxbx04zhengzhuang[i].name, "value": this.data.lxbx04zhengzhuang[i].value }
                  }
                  else {
                    json = { "checked": false, "name": this.data.lxbx04zhengzhuang[i].name, "value": this.data.lxbx04zhengzhuang[i].value }
                  }
                  arrlxbx04.push(json);
                }
              }
              else {
                this.setData({
                  lxbx04zhengzhuangH: true,
                }) 
                for (let i = 0; i < this.data.lxbx04zhengzhuang.length; i++) {
                  json = { "checked": false, "name": this.data.lxbx04zhengzhuang[i].name, "value": this.data.lxbx04zhengzhuang[i].value }
                  arrlxbx04.push(json);
                }
              }
                this.setData({
                  lxbx04zhengzhuang: arrlxbx04,
                }) 
              } catch {
                
              }
           
              try { 
                        if (res.data[0].sfwc != "") {
                        
                for (let i = 0; i < this.data.sfwc_check.length; i++) {
                  if (res.data[0].sfwc.includes(this.data.sfwc_check[i].name)) {
                    // 全选获取选中的值
                    json = { "checked": true, "name": this.data.sfwc_check[i].name, "value": this.data.sfwc_check[i].value }
                    // console.log('items:true' + i, json) 
                  }
                  else {
                    json = { "checked": false, "name": this.data.sfwc_check[i].name, "value": this.data.sfwc_check[i].value }
                    // console.log('items:false' + i, json)        
                  }
                  arrsfwc.push(json);
                }
                this.setData({
                  hsfwc: false,
                })
              }
              else {
                          for (let i = 0; i < this.data.sfwc_check.length; i++) {

                    json = { "checked": false, "name": this.data.sfwc_check[i].name, "value": this.data.sfwc_check[i].value }

                  arrsfwc.push(json);
                }
                this.setData({
                  hsfwc: true,
                })
              }
                this.setData({
                  sfwc_check: arrsfwc,
                }) 
              } catch {  
              }
              
              try { 
              if (res.data[0].zhengzhuang != "") {
                
                for (let i = 0; i < this.data.hospital_mz_lcbx.length; i++) {
                  if (res.data[0].zhengzhuang.includes(this.data.hospital_mz_lcbx[i].name)) {
                    // 全选获取选中的值
                    json = { "checked": true, "name": this.data.hospital_mz_lcbx[i].name, "value": this.data.hospital_mz_lcbx[i].value }
                    // console.log('items:true' + i, json) 
                  }
                  else {
                    json = { "checked": false, "name": this.data.hospital_mz_lcbx[i].name, "value": this.data.hospital_mz_lcbx[i].value }
                    // console.log('items:false' + i, json)        
                  }
                  arrzhengzhuang.push(json);
                }
               
              }
              else {
                for (let i = 0; i < this.data.hospital_mz_lcbx.length; i++) {

                  json = { "checked": false, "name": this.data.hospital_mz_lcbx[i].name, "value": this.data.hospital_mz_lcbx[i].value }

                  arrzhengzhuang.push(json);
                }
                
              }
                this.setData({
                  
                  hospital_mz_lcbx: arrzhengzhuang,
                  

                }) 
              } catch {
              }
              this.setData({
                name: res.data[0].name,
                sex: res.data[0].sex,
                sfz: res.data[0].sfz,
                address: res.data[0].address,
                phone: res.data[0].phone,
                fromwhere: res.data[0].fromwhere,
                lxbx04qtxx: res.data[0].lxbx04qtxx,
                memo: res.data[0].mz_memo
              
              }) 
              flag = parseInt(res.data[0].flag)+1,  //判断是否首次填写信息用
              //住院用信息
                zy_memo= res.data[0].zy_memo,
                  laifangmudi = res.data[0].laifangmudi,
                  beifangzhekeshi = res.data[0].beifangzhekeshi,
                  beifangzhename = res.data[0].beifangzhename,
                    // 下面火车 站信息用
                workaddress = res.data[0].workaddress,
                workphone = res.data[0].workphone,
                startwhere = res.data[0].startwhere,
                crosswhere = res.data[0].crosswhere,
                traininfo = res.data[0].traininfo,
                train_memo = res.data[0].train_memo,
           
              input_id =  res.data[0]._id  //删除前一条记录用
              
                        if (res.data[0].name && res.data[0].sfz &&
                          res.data[0].sex && res.data[0].address && res.data[0].phone) {
                          app.globalData.input_id = "0" + app.globalData.openid
                          // console.log('app.globalData.input_id', app.globalData.input_id)
                          
                          this.setData({
                            twocode_en: false,
                            btnEn: true,
                          })
                          if (parseInt(flag)==2){
                            // console.log('第二次添加', flag)
                              db.collection('base_zmyy').doc(res.data[0]._id).update({
                                data: {
                                  flag: "2",
                                }
                              })
                          }
                          else {
                            // console.log('不添加', flag)
                          }
                        }
            }
            else {
              console.log('没查询到数据', res.data.length)
            }
          })
        
      }
    })


  },
  lxbx: function (e) {
   let zmyygzs_lxbx = e.detail.value
    // console.log("checkbox-group", zmyygzs_lxbx)
    if (zmyygzs_lxbx !="") {
      // console.log("checkbox-true", zmyygzs_lxbx)
     
      this.setData({
        lxbx04zhengzhuangH: false,
        // lxbx04zhengzhuang: this.data.lxbx04zhengzhuang,
        twocode_en: true,
        btnEn: false,
      })
    }
    else {
      this.lxbx04();
      this.setData({
        lxbx04zhengzhuangH: true,
        twocode_en: true,
        btnEn: false,
      })
    }
  },
 
  // lxbxzz: function (e) {
  //   var vlxbxzz = e.detail.value
  //   // console.log("vsfwc", e)
  //   if (vlxbxzz == "其他") {
  //     console.log("checkbox-true", e.detail.value)
  //     this.setData({
  //       hvlxbxzz: false,
  //     })
  //   }
  //   else {
  //     console.log("checkbox-false", e.detail.value)
  //     this.setData({
  //       hvlxbxzz: true,
  //     })
  //   }
  // },

  formSubmit: function (e) {
    // console.log('form发生了submit事件，携带数据为：', e.detail.value)
    this.setData({
      btnEn: true, 
    })
    if (
      e.detail.value.name && e.detail.value.sfz && e.detail.value.sex && 
      e.detail.value.address) {
      if (e.detail.value.phone) {
        const db = wx.cloud.database()
        // console.log('删除数据', input_id)
        try {
            db.collection('base_zmyy').doc(input_id).remove({
      success: function (res) {
        // console.log('删除成功', input_id)
      }
          })
        } catch {}
        db.collection('base_zmyy').add({
          data: {
            name: e.detail.value.name,
            sfz: e.detail.value.sfz,
            sex: e.detail.value.sex,
            phone: e.detail.value.phone,
            address: e.detail.value.address,
            // lxbx: arrlxbxv,
            lxbx: e.detail.value.lxbx,
            sfwc: e.detail.value.sfwc,
            lxbx04zhengzhuang: e.detail.value.lxbx04zhengzhuang,
            lxbx4other: e.detail.value.lxbx4other,
            fromwhere: e.detail.value.fromwhere,
            zhengzhuang: e.detail.value.zhengzhuang,       
            addtime: util.formatTime(new Date()),
            mz_memo: e.detail.value.memo,         
            lxbx04qtxx: e.detail.value.lxbx04qtxx,
            // 下面住院信息用
            zy_memo: zy_memo,
            laifangmudi: laifangmudi,
            beifangzhekeshi: beifangzhekeshi,
            beifangzhename: beifangzhename,    
            flag: flag,   

             // 下面火车 站信息用
            workaddress: workaddress,
            workphone: workphone,
            startwhere: startwhere,
            crosswhere: crosswhere,
            traininfo: traininfo,
            train_memo: train_memo,
           
           
                
          }
          ,
          success: res => {
            // 在返回结果中会包含新创建的记录的 _id                  
            // wx.showToast({
            //   title: '新增记录成功',
            // })

            console.log('添加数据02', res)
            app.globalData.input_id = "0" + app.globalData.openid
            // app.globalData.input_link="station"
            wx.redirectTo({
              url: '/pages/createTwoCode/createTwoCode'
            })
            this.setData({ btnEn: false })
          },
          fail: err => {
            wx.showToast({
              icon: 'none',
              title: '新增记录失败,请找当值人员手工登记！'
            })
            // console.error('[数据库] [新增记录] 失败：', err)
          }
        })
       
      }
      else {
        // console.log('请更改地址信息：', e.detail.value)
        wx.showToast({
          icon: 'loading',
          title: '请允许获取手机',
        })
        this.setData({ btnEn: false, twocode_en: true, })
      }
    }
    else {
      // console.log('form发生了submit事件，携带数据为：', e.detail.value)
      wx.showToast({
        icon: 'loading',
        title: '请填全星号信息',
      })
      this.setData({ btnEn: false, twocode_en: true, })
    }
    // this.setData({ btnEn: false })
  },
  
})